package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired(required = false)
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody Category category, HttpSession session){
        long empId = (long)session.getAttribute("employee");
        category.setCreateUser(empId);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateUser(empId);
        category.setUpdateTime(LocalDateTime.now());
        categoryService.save(category);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page<Category>> findByPage(Integer page,Integer pageSize){
        Page<Category> resPage = categoryService.findByPage(page, pageSize);
        return R.success(resPage);
    }

    @DeleteMapping
    public R<String> delete(long id){
        categoryService.delete(id);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category,HttpSession session){
        long empId = (long)session.getAttribute("employee");
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(empId);
        categoryService.update(category);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> findAll(Integer type){
        List<Category> categoryList = categoryService.findByType(type);
        return R.success(categoryList);
    }
}
